package org.feit.findword;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;

public class FindWord extends Activity {

	private boolean mSavedGame;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
	}
	
	@Override
	protected void onStart() {
		super.onStart();
		checkSavedGame();
	}

	private void checkSavedGame() {
		mSavedGame = savedGame();
		if (mSavedGame) {
			Button btn = (Button) findViewById(R.id.btnNewGame);
			btn.setText(getString(R.string.restore_game));
		}else {
			Button btn = (Button) findViewById(R.id.btnNewGame);
			btn.setText(getString(R.string.new_game));
		}
	}
	public void onBtnClick(View v) {
		if (v.getId() == R.id.btnNewGame) {
			Intent intent = null;
			if (mSavedGame) {
				intent = new Intent("org.feit.findword.action.RESTORE_GAME");
			} else {
				intent = new Intent("org.feit.findword.action.NEW_GAME");
			}
			startActivity(intent);
		}
		if (v.getId() == R.id.btnHighScores) {
			Intent intent = new Intent(FindWord.this, HighScores.class);
			startActivity(intent);
		}
		if (v.getId() == R.id.btnSettings) {
			Intent intent = new Intent(FindWord.this, GameConfig.class);
			startActivity(intent);
		}
		if (v.getId() == R.id.btnQuit) {
			finish();
		}
	}

	public boolean savedGame() {
		SharedPreferences prefs = getSharedPreferences("prefs_game_file",
				MODE_PRIVATE);

		return prefs.getBoolean("activeGame", false);
	}
	
	private void clearSavedGame() {
		SharedPreferences prefs = getSharedPreferences("prefs_game_file",
				Context.MODE_PRIVATE);

		SharedPreferences.Editor editor = prefs.edit();
		editor.putBoolean("activeGame", false);
		editor.commit();

	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu m) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main_menu, m);

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if(item.getItemId() == R.id.help) {
			Intent intent = new Intent(this, Help.class);
			startActivity(intent);
		}
		if(item.getItemId() == R.id.delete_saved) {
			clearSavedGame();
			checkSavedGame();
		}
		return true;
	}
}